﻿
//using System;
//using System.Collections.Generic;
//using System.IO;
//using System.IO.IsolatedStorage;
//using System.Linq;
//using System.Net;
//using System.Windows;
//using System.Windows.Controls;
//using System.Windows.Documents;
//using System.Windows.Input;
//using System.Windows.Media;
//using System.Windows.Media.Animation;
//using System.Windows.Shapes;
//using Microsoft.Devices;
//using Microsoft.Phone.Controls;
//using Microsoft.Xna.Framework.Media;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;

// Directives
using Microsoft.Devices;
using System.IO;
using System.IO.IsolatedStorage;
using Microsoft.Phone.Shell;
using Microsoft.Phone.Tasks;
using Microsoft.Xna.Framework.Media;
using SMARTMobile.WinPhone;

namespace SMARTMobile.Views
{
    public partial class ChupHinhCuaHang
    {
        // Variables
        private int savedCounter = 0;
        PhotoCamera cam;
        MediaLibrary library = new MediaLibrary();

        // Holds the current flash mode.
        private string currentFlashMode;
        private bool _isNhapDuLieu;
        private string imageName;
        private bool _isInDoor;
        private bool _isOutDoor;
        private bool _isMerchandising; 

        private bool _isDuyetTTLamTuyen;
        // Holds the current resolution index.
        int currentResIndex = 0;
        public ChupHinhCuaHang()
        {
            InitializeComponent();
            this.Dispatcher.BeginInvoke(delegate()
            {
                ApplicationBarIconButton thoatButton = (ApplicationBarIconButton)ApplicationBar.Buttons[1];
                thoatButton.IsEnabled = false;

                ApplicationBarIconButton luuButton = (ApplicationBarIconButton)ApplicationBar.Buttons[3];
                luuButton.IsEnabled = false;
            });

            _isNhapDuLieu = false;
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            CreateCamera();
            string msg;
            if (NavigationContext.QueryString.TryGetValue("msg", out msg))
            {
                if (!string.IsNullOrEmpty(msg) )
                {
                    if (msg.Contains("NhapDuLieuIn"))
                    {
                        _isInDoor = true;
                    }

                    if (msg.Contains("NhapDuLieuOut"))
                    {
                        _isOutDoor = true;
                    }

                    if (msg.Contains("Merchandising"))
                    {
                        _isMerchandising = true;
                    }

                    if (msg.Contains("DuyetTTLamTuyen"))
                    {
                        _isDuyetTTLamTuyen = true;
                    }

                    string tempName = msg.Split(';')[1];
                    imageName = tempName;
                }
            }
        }

        private void CreateCamera()
        {
            // Check to see if the camera is available on the device.
            if ((PhotoCamera.IsCameraTypeSupported(CameraType.Primary) == true) ||
                 (PhotoCamera.IsCameraTypeSupported(CameraType.FrontFacing) == true))
            {
                // Initialize the camera, when available.
                //if (PhotoCamera.IsCameraTypeSupported(CameraType.FrontFacing))
                //{
                //    // Use front-facing camera if available.
                //    cam = new Microsoft.Devices.PhotoCamera(CameraType.FrontFacing);
                //}
                //else
                //{
                // Otherwise, use standard camera on back of device.
                cam = new Microsoft.Devices.PhotoCamera(CameraType.Primary);
                ////}

                // Event is fired when the PhotoCamera object has been initialized.
                cam.Initialized += new EventHandler<Microsoft.Devices.CameraOperationCompletedEventArgs>(cam_Initialized);

                // Event is fired when the capture sequence is complete.
                cam.CaptureCompleted += new EventHandler<CameraOperationCompletedEventArgs>(cam_CaptureCompleted);

                // Event is fired when the capture sequence is complete and an image is available.
                cam.CaptureImageAvailable += new EventHandler<Microsoft.Devices.ContentReadyEventArgs>(cam_CaptureImageAvailable);

                // Event is fired when the capture sequence is complete and a thumbnail image is available.
                cam.CaptureThumbnailAvailable += new EventHandler<ContentReadyEventArgs>(cam_CaptureThumbnailAvailable);

                // The event is fired when auto-focus is complete.
                cam.AutoFocusCompleted += new EventHandler<CameraOperationCompletedEventArgs>(cam_AutoFocusCompleted);

                // The event is fired when the viewfinder is tapped (for focus).
                viewfinderCanvas.Tap += new EventHandler<System.Windows.Input.GestureEventArgs>(focus_Tapped);

                // The event is fired when the shutter button receives a half press.
                CameraButtons.ShutterKeyHalfPressed += OnButtonHalfPress;

                // The event is fired when the shutter button receives a full press.
                CameraButtons.ShutterKeyPressed += OnButtonFullPress;

                // The event is fired when the shutter button is released.
                CameraButtons.ShutterKeyReleased += OnButtonRelease;

                //Set the VideoBrush source to the camera.
                viewfinderBrush.SetSource(cam);
            }
            else
            {
                // The camera is not supported on the device.
                this.Dispatcher.BeginInvoke(delegate()
                {
                    // Write message.
                    //txtDebug.Text = "A Camera is not available on this device.";
                });

                // Disable UI.
                //ShutterButton.IsEnabled = false;
                //FlashButton.IsEnabled = false;
                //AFButton.IsEnabled = false;
                //ResButton.IsEnabled = false;
            }
        }

        void cam_Initialized(object sender, Microsoft.Devices.CameraOperationCompletedEventArgs e)
        {
            if (e.Succeeded)
            {
                this.Dispatcher.BeginInvoke(delegate()
                {
                    // Write message.
                    //txtDebug.Text = "Camera initialized.";

                    // Set flash button text.
                    // FlashButton.Content = "Fl:" + cam.FlashMode.ToString();
                });
            }
        }

        void cam_CaptureCompleted(object sender, CameraOperationCompletedEventArgs e)
        {
            // Increments the savedCounter variable used for generating JPEG file names.
            savedCounter++;            
        }

        void cam_CaptureImageAvailable(object sender, Microsoft.Devices.ContentReadyEventArgs e)
        {
            string fileName = savedCounter + ".jpg";

            try
            {   // Write message to the UI thread.
                Deployment.Current.Dispatcher.BeginInvoke(delegate()
                {
                    //txtDebug.Text = "Captured image available, saving picture.";
                });

                // Save picture to the library camera roll.
                library.SavePictureToCameraRoll(fileName, e.ImageStream);

                // Write message to the UI thread.
                Deployment.Current.Dispatcher.BeginInvoke(delegate()
                {
                    //txtDebug.Text = "Picture has been saved to camera roll.";

                });

                // Set the position of the stream back to start
                e.ImageStream.Seek(0, SeekOrigin.Begin);

                // Save picture as JPEG to isolated storage.
                using (IsolatedStorageFile isStore = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    using (IsolatedStorageFileStream targetStream = isStore.OpenFile(fileName, FileMode.Create, FileAccess.Write))
                    {
                        // Initialize the buffer for 4KB disk pages.
                        byte[] readBuffer = new byte[4096];
                        int bytesRead = -1;

                        // Copy the image to isolated storage. 
                        while ((bytesRead = e.ImageStream.Read(readBuffer, 0, readBuffer.Length)) > 0)
                        {
                            targetStream.Write(readBuffer, 0, bytesRead);
                        }
                    }
                }

                // Write message to the UI thread.
                Deployment.Current.Dispatcher.BeginInvoke(delegate()
                {
                    //txtDebug.Text = "Picture has been saved to isolated storage.";

                });
            }
            finally
            {
                // Close image stream
                e.ImageStream.Close();
            }

        }

        public void cam_CaptureThumbnailAvailable(object sender, ContentReadyEventArgs e)
        {
            string fileName = savedCounter + "_th.jpg";

            try
            {
                // Write message to UI thread.
                Deployment.Current.Dispatcher.BeginInvoke(delegate()
                {
                    //txtDebug.Text = "Captured image available, saving thumbnail.";
                });

                // Save thumbnail as JPEG to isolated storage.
                using (IsolatedStorageFile isStore = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    using (IsolatedStorageFileStream targetStream = isStore.OpenFile(fileName, FileMode.Create, FileAccess.Write))
                    {
                        // Initialize the buffer for 4KB disk pages.
                        byte[] readBuffer = new byte[4096];
                        int bytesRead = -1;

                        // Copy the thumbnail to isolated storage. 
                        while ((bytesRead = e.ImageStream.Read(readBuffer, 0, readBuffer.Length)) > 0)
                        {
                            targetStream.Write(readBuffer, 0, bytesRead);
                        }
                    }
                }

                // Write message to UI thread.
                Deployment.Current.Dispatcher.BeginInvoke(delegate()
                {
                    //txtDebug.Text = "Thumbnail has been saved to isolated storage.";

                });
            }
            finally
            {
                // Close image stream
                ////e.ImageStream.Close();
            }

            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                ////NavigationService.Navigate(new Uri("/Views/ChupHinhPage.xaml?msg=" + fileName, UriKind.Relative)); 
                BitmapImage bmp = new BitmapImage();
                ////bmp = new BitmapImage(new Uri(fileName, UriKind.Relative));
                bmp.SetSource(e.ImageStream);
                ImageBrush ib = new ImageBrush();
                ib.ImageSource = bmp;
                viewfinderCanvas.Background = ib;
              
            });
        }

        void cam_AutoFocusCompleted(object sender, CameraOperationCompletedEventArgs e)
        {
            Deployment.Current.Dispatcher.BeginInvoke(delegate()
            {
                // Write message to UI.
                //txtDebug.Text = "Auto focus has completed.";

                // Hide the focus brackets.
                focusBrackets.Visibility = Visibility.Collapsed;

            });
        }

        void focus_Tapped(object sender, System.Windows.Input.GestureEventArgs e)
        {
            if (cam != null)
            {
                if (cam.IsFocusAtPointSupported == true)
                {
                    try
                    {
                        // Determine location of tap.
                        Point tapLocation = e.GetPosition(viewfinderCanvas);

                        // Position focus brackets with estimated offsets.
                        focusBrackets.SetValue(Canvas.LeftProperty, tapLocation.X - 30);
                        focusBrackets.SetValue(Canvas.TopProperty, tapLocation.Y - 28);

                        // Determine focus point.
                        double focusXPercentage = tapLocation.X / viewfinderCanvas.Width;
                        double focusYPercentage = tapLocation.Y / viewfinderCanvas.Height;

                        // Show focus brackets and focus at point
                        focusBrackets.Visibility = Visibility.Visible;
                        cam.FocusAtPoint(focusXPercentage, focusYPercentage);

                        // Write a message to the UI.
                        this.Dispatcher.BeginInvoke(delegate()
                        {
                            //txtDebug.Text = String.Format("Camera focusing at point: {0:N2} , {1:N2}", focusXPercentage, focusYPercentage);
                        });
                    }
                    catch (Exception focusError)
                    {
                        // Cannot focus when a capture is in progress.
                        this.Dispatcher.BeginInvoke(delegate()
                        {
                            // Write a message to the UI.
                            //txtDebug.Text = focusError.Message;
                            // Hide focus brackets.
                            focusBrackets.Visibility = Visibility.Collapsed;
                        });
                    }
                }
                else
                {
                    // Write a message to the UI.
                    this.Dispatcher.BeginInvoke(delegate()
                    {
                        //txtDebug.Text = "Camera does not support FocusAtPoint().";
                    });
                }
            }
        }

        private void OnButtonHalfPress(object sender, EventArgs e)
        {
            if (cam != null)
            {
                // Focus when a capture is not in progress.
                try
                {
                    this.Dispatcher.BeginInvoke(delegate()
                    {
                        //txtDebug.Text = "Half Button Press: Auto Focus";
                    });

                    cam.Focus();
                }
                catch (Exception focusError)
                {
                    // Cannot focus when a capture is in progress.
                    this.Dispatcher.BeginInvoke(delegate()
                    {
                        //txtDebug.Text = focusError.Message;
                    });
                }
            }
        }

        // Capture the image with a full button press using the hardware shutter button.
        private void OnButtonFullPress(object sender, EventArgs e)
        {
            if (cam != null)
            {
                cam.CaptureImage();
            }
        }

        // Cancel the focus if the half button press is released using the hardware shutter button.
        private void OnButtonRelease(object sender, EventArgs e)
        {

            if (cam != null)
            {
                cam.CancelFocus();
            }
        }

        private void ApplicationBarIconButton_OnClick(object sender, EventArgs e)
        {
            this.Dispatcher.BeginInvoke(delegate()
            {
                ApplicationBarIconButton thoatButton = (ApplicationBarIconButton) ApplicationBar.Buttons[1];
                thoatButton.IsEnabled = true;
                ApplicationBarIconButton chuphinhButton = (ApplicationBarIconButton)ApplicationBar.Buttons[2];
                chuphinhButton.IsEnabled = false;
                ApplicationBarIconButton luuButton = (ApplicationBarIconButton)ApplicationBar.Buttons[3];
                luuButton.IsEnabled = true;

                ApplicationBarIconButton homeButton = (ApplicationBarIconButton) ApplicationBar.Buttons[0];
                homeButton.IsEnabled = true;
            });

            if (cam != null)
            {
                try
                {
                    //CCT.Show();
                    // Start image capture.
                    cam.CaptureImage();
                }
                catch (Exception ex)
                {
                    this.Dispatcher.BeginInvoke(delegate()
                    {
                        // Cannot capture an image until the previous capture has completed.
                        //txtDebug.Text = ex.Message;
                    });
                }
            }
        }

        private void Thoat_OnClick(object sender, EventArgs e)
        {
            if (cam != null)
            {
                cam.Dispose();
            }

            if (_isInDoor || _isOutDoor || _isMerchandising)
            {
                string currentView = string.Empty;
                if (_isInDoor)
                {
                    currentView = "ExplainInDoor";
                }

                if (_isOutDoor)
                {
                    currentView = "ExplainOutDoor";
                }

                if (_isMerchandising)
                {
                    currentView = "ExplainMerchandising";
                }

                NavigationService.Navigate(new Uri("/Views/NhapDuLieuPage.xaml?msg=" + currentView + ";" + imageName, UriKind.Relative));
            }
            else if (_isDuyetTTLamTuyen)
            {
                NavigationService.Navigate(new Uri("/Views/DuyetTTLamTuyenPage.xaml?msg=ThayTheHinh", UriKind.Relative));
            }
            else
            {
                NavigationService.Navigate(new Uri("/Views/ChupHinhMainPage.xaml?msg=", UriKind.Relative));
            }        
        }


        private void Xoa_OnClick(object sender, EventArgs e)
        {
            if (cam != null)
            {
                CreateCamera();
                viewfinderCanvas.Background = viewfinderBrush;

                this.Dispatcher.BeginInvoke(delegate()
                {
                    ApplicationBarIconButton thoatButton = (ApplicationBarIconButton)ApplicationBar.Buttons[1];
                    thoatButton.IsEnabled = false;
                    ApplicationBarIconButton chuphinhButton = (ApplicationBarIconButton)ApplicationBar.Buttons[2];
                    chuphinhButton.IsEnabled = true;
                    ApplicationBarIconButton luuButton = (ApplicationBarIconButton)ApplicationBar.Buttons[3];
                    luuButton.IsEnabled = false;

                    ApplicationBarIconButton homeButton = (ApplicationBarIconButton) ApplicationBar.Buttons[0];
                    homeButton.IsEnabled = true;
                });
            }
        }


        private void Luu_OnClick(object sender, EventArgs e)
        {
            if (cam != null)
            {
                cam.Dispose();
            }

            if (_isInDoor || _isOutDoor || _isMerchandising)
            {
                string currentView = string.Empty;
                if (_isInDoor)
                {
                    currentView = "ExplainInDoor";
                }
                
                if (_isOutDoor)
                {
                    currentView = "ExplainOutDoor";
                }

                if (_isMerchandising)
                {
                    currentView = "ExplainMerchandising";
                }

                NavigationService.Navigate(new Uri("/Views/NhapDuLieuPage.xaml?msg=" + currentView + ";" + imageName, UriKind.Relative)); 
            }
            else if (_isDuyetTTLamTuyen)
            {
                NavigationService.Navigate(new Uri("/Views/DuyetTTLamTuyenPage.xaml?msg=ThayTheHinh", UriKind.Relative)); 
            }
            else
            {
                NavigationService.Navigate(new Uri("/Views/ChupHinhMainPage.xaml?msg=" + "Step1", UriKind.Relative)); 
            }            
        }
    }
}
